package com.yld.car.market;

import java.util.HashMap;

import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.yld.car.common.ConstantUtils;
import com.yld.car.common.NetworkProgressUtils;
import com.yld.car.domain.UserInfo;
import com.yld.car.market.tab.TabActivityGroup;

public class LoginActivity extends BaseActivity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);

		// 自定义标题栏
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.login);
		utils = NetworkProgressUtils.getInstance();
		// 设置布局
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		((TextView) findViewById(R.id.title)).setText("登录");

		ListView listView1 = (ListView) findViewById(R.id.list1);

		listView1.setAdapter(new LoginAdapter(this));
		// ListView listView2 = (ListView) findViewById(R.id.list2);
		// listView2.setAdapter(new Login2Adapter(this));
		// listView2.setOnItemClickListener(onItemClickTwoListener);
		settings = getSharedPreferences("user", MODE_PRIVATE);
		editor = settings.edit();
	}

	OnItemClickListener onItemClickTwoListener = new OnItemClickListener() {

		@Override
		public void onItemClick(AdapterView<?> adapterView, View view,
				int position, long id) {

			Intent intent = new Intent();
			intent.setClass(LoginActivity.this, ForgetActivity.class);
			startActivity(intent);
		}
	};
	private String uname = "";
	private String pwd = "";

	public class LoginAdapter extends BaseAdapter {
		private Context context;
		private LayoutInflater mInflater;
		private TextWatcher textWatcher1 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				uname = paramCharSequence.toString();
			}
		};
		private TextWatcher textWatcher2 = new TextWatcher() {
			public void afterTextChanged(Editable paramEditable) {
			}

			public void beforeTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
			}

			public void onTextChanged(CharSequence paramCharSequence,
					int paramInt1, int paramInt2, int paramInt3) {
				pwd = paramCharSequence.toString();
			}
		};

		public LoginAdapter(Context paramContext) {
			this.mInflater = LayoutInflater.from(paramContext);
			this.context = paramContext;
		}

		public int getCount() {
			return 2;
		}

		public Object getItem(int paramInt) {
			return "";
		}

		public long getItemId(int paramInt) {
			return paramInt;
		}

		public View getView(int paramInt, View paramView,
				ViewGroup paramViewGroup) {
			if (paramInt == 0) {
				paramView = this.mInflater.inflate(
						R.layout.base_list_items_input, null);
				EditText localEditText2 = (EditText) paramView
						.findViewById(R.id.itemUserName);
				localEditText2.setHint("登录手机号");
				localEditText2.setInputType(3);
				localEditText2.addTextChangedListener(this.textWatcher1);

			}

			if (paramInt == 1) {
				paramView = this.mInflater.inflate(
						R.layout.base_list_items_input_passwd, null);
				EditText localEditText1 = (EditText) paramView
						.findViewById(R.id.itemPwd);
				localEditText1.setHint("密码");
				localEditText1.addTextChangedListener(this.textWatcher2);
				localEditText1.setOnKeyListener(new View.OnKeyListener() {
					public boolean onKey(View paramView, int paramInt,
							KeyEvent paramKeyEvent) {

						return false;
					}
				});

			}

			return paramView;
		}

		public boolean isEnabled(int paramInt) {
			return false;
		}
	}

	private NetworkProgressUtils utils;

	public void onAction(View v) {

		// System.out.println("uname==="+uname+",pwd=="+pwd);

		int id = v.getId();
		switch (id) {
		case R.id.loginButton:
			if (validate()) {
				new Thread(new Runnable() {

					@Override
					public void run() {
						/*
						 * GetLogin(string adminName, string adminPass) 参数一：用户名
						 * 如：15823912195 参数二：用户密码 如：123456/563697
						 * 
						 * 成功返回： { "result":"1", "data":{
						 * "userphone":"15823912195", --用户手机号（其实就是用户登录名）
						 * "username":"刘强"} --用户姓名 }
						 */

						HashMap<String, String> allParams = new HashMap<String, String>();

						allParams.put("adminName", uname);
						allParams.put("adminPass", pwd);

						Object o = utils
								.getWebservicesByData(
										ConstantUtils.NAME_SPACE,
										ConstantUtils.ALL_METHROD_NAME.get(8),
										ConstantUtils.NAME_SPACE
												+ ConstantUtils.ALL_METHROD_NAME
														.get(8),
										ConstantUtils.GET_LOGIN_URL, allParams);

						// System.out.println("login===>"+o);

						UserInfo u = utils.parseUserInfo(o.toString(), pwd);

						if (u != null) {
							u.setFinishLogin(true);
							Intent intent = new Intent();
							intent.setClass(getApplicationContext(),
									TabActivityGroup.class);
							startActivity(intent);

							writeObject(u, "userInfo");
							finish();
							// editor.putString("uname", uname);
							// editor.putBoolean("isFinishLogin", true);
							// editor.putString("pwd", pwd);
							// editor.commit();
						} else {

							mHandler.sendEmptyMessage(0);
						}
						// System.out.println("uuuuu=="+u);
						// if (o != null) {
						// // System.out.println("o====" + o.toString());
						// if ((o.toString().indexOf("returnval")) > -1) {
						//
						// } else {
						//
						// // MyApplication application = (MyApplication)
						// // getApplication();
						// //
						// // application.setFinishLogin(true);
						//
						// }
						//
						// }

					}
				}).start();
			}
			break;

		case R.id.forgetPwdButton:
			Intent intent = new Intent();
			intent.setClass(LoginActivity.this, ForgetActivity.class);
			startActivity(intent);
			break;

		case R.id.registerButton:
			Intent intent1 = new Intent();
			intent1.setClass(this, RegisterCompanyActivity.class);
			startActivity(intent1);
			break;
		}

	}

	private SharedPreferences settings;
	private SharedPreferences.Editor editor;
	private Handler mHandler = new Handler() {

		public void handleMessage(android.os.Message msg) {

			Toast.makeText(getApplicationContext(), "用户名或密码错误，登录失败，请重试！",
					Toast.LENGTH_SHORT).show();

		}
	};

	private boolean validate() {
		if (this.uname.equals("")) {
			showDialog("用户名称是必填项！");
			return false;
		}
		if (this.pwd.equals("")) {
			showDialog("用户密码是必填项！");
			return false;
		}
		return true;
	}

	protected void showDialog(String paramString) {
		AlertDialog.Builder localBuilder = new AlertDialog.Builder(this);
		localBuilder.setTitle("提示");
		localBuilder.setMessage(paramString);
		localBuilder.setCancelable(false);
		localBuilder.setPositiveButton("确定",
				new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface paramDialogInterface,
							int paramInt) {
					}
				});
		localBuilder.create().show();
	}

	private class Login2Adapter extends BaseAdapter {
		private Context context;
		private LayoutInflater mInflater;

		public Login2Adapter(Context paramContext) {
			this.context = paramContext;
			this.mInflater = LayoutInflater.from(paramContext);
		}

		public int getCount() {
			return 1;
		}

		public Object getItem(int paramInt) {
			return "";
		}

		public long getItemId(int paramInt) {
			return paramInt;
		}

		public View getView(int paramInt, View paramView,
				ViewGroup paramViewGroup) {
			View localView = this.mInflater.inflate(
					R.layout.base_list_items_simple, null);
			TextView localTextView = (TextView) localView
					.findViewById(R.id.itemContent);
			localTextView.setTextColor(this.context.getResources()
					.getColorStateList(R.color.font_gray_light_2));
			localTextView.setText("忘记密码，在这找回");
			((ImageView) localView.findViewById(R.id.nextStep))
					.setVisibility(View.VISIBLE);
			localView
					.setBackgroundResource(android.R.drawable.list_selector_background);
			return localView;
		}

		public boolean isEnabled(int paramInt) {
			return true;
		}
	}
}
